package com.sdhs.projectschedule.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sdhs.basicinfo.domain.GcFoundationConfigurationReminder;
import com.sdhs.basicinfo.mapper.GcFoundationConfigurationReminderMapper;
import com.sdhs.common.utils.DateUtils;
import com.sdhs.common.utils.SecurityUtils;
import com.sdhs.common.utils.StringUtils;
import com.sdhs.projectschedule.domain.GcProgressMasterPlanMark;
import com.sdhs.projectschedule.mapper.GcProgressMasterPlanMarkMapper;
import com.sdhs.projectschedule.mapper.GcProgressMasterPlanMarkTempMapper;
import com.sdhs.projectschedule.mapper.GcProgressMasterPlanTempMapper;
import com.sdhs.projectschedule.service.IGcProgressMasterPlanMarkService;
import com.sdhs.projectstart.domain.ProjectDept;
import com.sdhs.projectstart.mapper.ProjectDeptMapper;
import com.sdhs.system.domain.MessageInfoDO;
import com.sdhs.system.service.IMessageInfoService;
import com.sdhs.workflow.utils.UnifyApiUtils;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;


/**
 * 项目进度控制--总体计划管理子--总体计划制定Service业务层处理
 *
 * @author ww
 * @date 2025-03-22
 */
@Service
public class GcProgressMasterPlanMarkServiceImpl implements IGcProgressMasterPlanMarkService {
	
    @Autowired
    private GcProgressMasterPlanMarkMapper gcProgressMasterPlanMarkMapper;
    
    @Autowired
    private ProjectDeptMapper projectDeptMapper;
    
    @Autowired
    private GcFoundationConfigurationReminderMapper gcFoundationConfigurationReminderMapper;
    
    @Autowired
    private IMessageInfoService messageInfoService;
    
    @Autowired
    private GcProgressMasterPlanMarkTempMapper gcProgressMasterPlanMarkTempMapper;
    
    @Autowired
    private GcProgressMasterPlanTempMapper gcProgressMasterPlanTempMapper;
    
    /**
     * 定时任务查询需要发送预警消息的计划，同时修改预警标识
     */
    public void handlePlanMarkTask() {
    	String currentTimeStr = DateUtils.getDate();
    	GcFoundationConfigurationReminder reminder = gcFoundationConfigurationReminderMapper.selectGcFoundationConfigurationReminderById(1L);
    	Long advanceDays = reminder.getAdvanceDays();
    	List<GcProgressMasterPlanMark> planMarkList = gcProgressMasterPlanMarkMapper.selectPlanMarkTask(currentTimeStr, advanceDays);
    	if (CollectionUtil.isNotEmpty(planMarkList)) {
    		for (GcProgressMasterPlanMark planMark : planMarkList) {
    			getWarningSigns(planMark.getId(), planMark.getPlanName(), planMark.getPlanEndTime(), planMark.getPracticeEndTime());
    		}
    	}
    	gcProgressMasterPlanMarkMapper.updateWarningSignsTask(currentTimeStr, advanceDays);
    }
    
    /**
     * 总体计划制定流程审批通过后，处理预警标识字段的值
     * @param planMarkList
     */
    public void planMarkWarn(List<GcProgressMasterPlanMark> planMarkList) {
    	if (CollectionUtil.isNotEmpty(planMarkList)) {
    		for (GcProgressMasterPlanMark planMark : planMarkList) {
    			String warningSigns = getWarningSigns(planMark.getId(), planMark.getPlanName(), planMark.getPlanEndTime(), planMark.getPracticeEndTime());
    			planMark.setWarningSigns(warningSigns);
    	        gcProgressMasterPlanMarkMapper.updateGcProgressMasterPlanMark(planMark);
    		}
    	}
    }
    
    /**
     * 【计划变更】流程审批通过后，用变更的数据覆盖【总体计划制定】的数据，同时触发预警标识。
     * @param planId
     * @param planMarkList
     */
    public void planMarkCover(Long planId, List<GcProgressMasterPlanMark> planMarkList) {
    	gcProgressMasterPlanMarkMapper.deleteGcProgressMasterPlanMarkByPlanId(planId);
    	if (CollectionUtil.isNotEmpty(planMarkList)) {
    		String createBy = SecurityUtils.getUsername();
    		Date createTime = DateUtils.getNowDate();
    		for (GcProgressMasterPlanMark planMark : planMarkList) {
    			planMark.setPlanId(planId);
    			planMark.setCreateBy(createBy);
    			planMark.setCreateTime(createTime);
    			gcProgressMasterPlanMarkMapper.insertGcProgressMasterPlanMark(planMark);
    			String warningSigns = getWarningSigns(planMark.getId(), planMark.getPlanName(), planMark.getPlanEndTime(), planMark.getPracticeEndTime());
    			planMark.setWarningSigns(warningSigns);
    	        gcProgressMasterPlanMarkMapper.updateGcProgressMasterPlanMark(planMark);
    		}
    	}
    }

    /**
     * 查询项目进度控制--总体计划管理子--总体计划制定列表
     *
     * @param planId 项目进度控制--总体计划管理planId
     * @return 项目进度控制--总体计划管理子--总体计划制定
     */
    @Override
    public List<GcProgressMasterPlanMark> selectGcProgressMasterPlanMarkList(String planId) {
        return gcProgressMasterPlanMarkMapper.selectGcProgressMasterPlanMarkList(planId);
    }

    /**
     * 修改保存项目进度控制--总体计划管理子--总体计划制定
     *
     * @param gcProgressMasterPlanMark 项目进度控制--总体计划管理子--总体计划制定
     * @return 结果
     */
    @Override
    public int updateGcProgressMasterPlanMarkList(GcProgressMasterPlanMark mark)
    {
    	String warningSigns = getWarningSigns(mark.getId(), mark.getPlanName(), mark.getPlanEndTime(), mark.getPracticeEndTime());
    	mark.setWarningSigns(warningSigns);
    	int result = gcProgressMasterPlanMarkMapper.updateGcProgressMasterPlanMark(mark);
    	// 您有尚未发起的总体计划变更，保存后将删除变更数据
    	if (mark.getTempPlanId() != null) {
    		gcProgressMasterPlanTempMapper.deleteGcProgressMasterPlanTempById(mark.getTempPlanId());
    		gcProgressMasterPlanMarkTempMapper.deleteGcProgressMasterPlanMarkTempByPlanId(mark.getTempPlanId());
    	}
    	return result;
    }
    
    /**
     * 根据计划完工时间、实际完工时间来判断预警标识
     * 
     * 1.当实际完工时间有值时
     * 例如：计划完工时间为04-30
     * 如果实际完工时间在04-30之前，则预警标识为1：正常
     * 如果实际完工时间在04-30之后，则预警标识为3：超时
     * 
     * 2.当实际完工时间没值时，则取当前时间
     * 例如：预警提前天数为15天，计划完工时间为04-30，往前推15天为04-15
     * 如果当前时间在04-15之前，则预警标识为1：正常
     * 如果当前时间在04-15和04-30之间，则预警标识为2：预警，同时需要给项目经理发消息（我的消息、企业微信）
     * 如果当前时间在04-30之后，则预警标识为3：超时
     * 
     * @param planEndTime
     * @param practiceEndTime
     * @return
     */
    public String getWarningSigns(Long id, String planName, Date planEndTime, Date practiceEndTime) {
    	String warningSigns = null;
    	if (planEndTime != null) {
    		if (practiceEndTime != null) {
    			String dayStr = DateUtils.dayDistance(planEndTime, practiceEndTime);
				Long day = Long.valueOf(dayStr);
				if (day >= 0) {
					// 1：正常
					warningSigns = "1";
				} else {
					// 3：超时
					warningSigns = "3";
				}
    		} else {
	    		GcFoundationConfigurationReminder reminder = gcFoundationConfigurationReminderMapper.selectGcFoundationConfigurationReminderById(1L);
	    		if (reminder != null) {
	    			Long advanceDays = reminder.getAdvanceDays();
	    			String currentTimeStr = DateUtils.getDate();
	    			Date currentTime = DateUtils.parseDate(currentTimeStr);
					String dayStr = DateUtils.dayDistance(planEndTime, currentTime);
					Long day = Long.valueOf(dayStr);
					if (day > advanceDays) {
						// 1：正常
						warningSigns = "1";
					} else if (day >= 0 && day <= advanceDays) {
						// 2：预警
						warningSigns = "2";
						if ("0".equals(reminder.getEnableState())) {
							ProjectDept projectDept = projectDeptMapper.selectProjectDeptByPlanMarkId(id);
			    			if (projectDept != null && StringUtils.isNotEmpty(projectDept.getManager())) {
			    				String projectName = projectDept.getProjectName();
			    				String planEndTimeStr = DateUtils.dateTime(planEndTime);
			    				String titleTemplate = "项目名称：{}，计划名称：{}，预警提醒";
			    				String contentTemplate = "项目名称：{}，计划名称：{}，计划完工时间：{}，预警提醒";
			    				String title = StrUtil.format(titleTemplate, projectName, planName);
			    				String content = StrUtil.format(contentTemplate, projectName, planName, planEndTimeStr);
			    				String type = "gc_progress_master_plan_mark";
			    				Integer msgCount = messageInfoService.countByContent(title, content, projectDept.getManager());
			    				if (msgCount == 0) {
				    				// 我的消息
				    				List<MessageInfoDO> myMsgList = messageInfoService.getMsgList(title, content, id, type, projectDept.getManager());
				    				messageInfoService.sendMsgBatch(myMsgList);
				    				// 企业微信
				    				List<String> users = new ArrayList<String>();
				    				users.add(projectDept.getUserId());
				    				UnifyApiUtils.sendWXWORKTextMsg(title, users, "system", content);
			    				}
			    			}
						}
					} else {
						// 3：超时
						warningSigns = "3";
					}
	    		}
    		}
    	}
    	return warningSigns;
    }

    /**
     * 删除项目进度控制--施工日志信息
     *
     * @param id 项目进度控制--施工日志主键
     * @return 结果
     */
    @Override
    public int deleteGcProgressMasterPlanMarkById(Long id)
    {
        GcProgressMasterPlanMark gcProgressMasterPlanMark = gcProgressMasterPlanMarkMapper.selectGcProgressMasterPlanMarkById(id);
        gcProgressMasterPlanMark.setIsDelete("1");
        return gcProgressMasterPlanMarkMapper.updateGcProgressMasterPlanMark(gcProgressMasterPlanMark);
    }
}
